/**
 * Copyright (c) OpenSpug Organization. https://github.com/openspug/spug
 * Copyright (c) <spug.dev@gmail.com>
 * Released under the AGPL-3.0 License.
 */
import React from 'react';
import { Card,Table } from 'antd';
import styles from '../index/index.css'
import '../index/index.css'
import { yuntuVisit,getOverview,loginList,systemWarningLine,backstageList,systemListData} from '../../../api/AccountApi'
import { DatePicker, Modal,Pagination,List  } from 'antd';
import moment from 'moment';
import echarts from 'echarts'
// 引入柱状图
import  '../../../../node_modules/echarts/lib/chart/bar';
// 引入提示框和标题组件
import '../../../../node_modules/echarts/lib/component/tooltip';
import '../../../../node_modules/echarts/lib/component/title';

const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';

class HomeInfo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            timesList:[],
            chartsModule:[],
            listModule:[],
            btnIndex:0,
            params:{
                cloudNum:0,
                backendNum:0,
                errorCatchNum:0,
                apiWarningNum:0,
            },
            loginList:{
                name:'系统登录日志',
                columns:[
                    {
                        title:'登录用户',
                        dataIndex:'nickname',
                        key:'nickname'
                    },
                    {
                        title:'登录时间',
                        dataIndex:'login_time',
                        key:'login_time'
                    },
                    {
                        title:'IP',
                        dataIndex:'ip',
                        key:'ip'
                    },
                    {
                        title:'归属地',
                        dataIndex:'location',
                        key:'location'
                    }
                ],
                dataSource:[]
            },
            loginlistData:[],
            yuntuVisitList:{
                name:'云图访问日志',
                columns:[
                    {
                        title:'访问时间',
                        dataIndex:'access_time',
                        key:'access_time'
                    },
                    {
                        title:'访问用户',
                        dataIndex:'nickname',
                        key:'nickname'
                    },
                    {
                        title:'访问云图',
                        dataIndex:'detail',
                        key:'detail'
                    },

                    {
                        title:'访问IP',
                        dataIndex:'ip',
                        key:'ip'
                    }
                ],
            },
            backOperateList:{
                name:'后台操作日志',
                columns:[
                    {
                        title:'操作用户',
                        dataIndex:'nickname',
                        key:'nickname'
                    },
                    {
                        title:'操作IP',
                        dataIndex:'ip',
                        key:'ip'
                    },
                    {
                        title:'操作时间',
                        dataIndex:'access_time',
                        key:'access_time'
                    },
                    {
                        title:'操作详情',
                        dataIndex:'detail',
                        key:'detail'
                    }
                ],
                dataSource:[]
            },
            backStageData:[],
            visitListData:[],
            visitTotal:0,
            currentPage1:1,
            currentPage2:1,
            currentPage3:1,
            currentPage4:1,
            pageSize:5,
            loginTotal:0,
            backstageTotal:0,
            yuntuCharts:{
                name:'云图访问分布'
            },
            systemCharts:{
                name:'系统报警趋势'
            },
            leftChart:[],
            rightChart:[],
            visitXData:[],
            visitBarData:[],
            errorXData:[],
            errorLineData:[],
            modalContent:[],
            showModal:false,
            activeBtn1:1,
            activeBtn2:1,
            activeBtn3:1,
            secondDate:[],
            firstDate:[],
            timeType1:1,
            timeType2:1,
            isAPI:1,
            isRoot:false,
            typeName:'API报警趋势',
            modalSQLColumns:[
                {
                    key:'info',
                    title:'SQL',
                    dataIndex:'info',
                    width:200
                },
                {
                    key:'time_day',
                    dataIndex:'time_day',
                    title:'日期'
                },
                {
                    key:'duration',
                    dataIndex:'duration',
                    title:'执行事件'
                },
                {
                    key:'memory',
                    dataIndex:'memory',
                    title:'消耗内存'
                },
                {
                    key:'memoryDiff',
                    dataIndex:'memoryDiff',
                    title:'内存差异'
                },
                {
                    key:'num',
                    dataIndex:'num',
                    title:'预警次数'
                }
            ],
            modalAPIColumns:[
                {
                    key:'time_day',
                    dataIndex:'time_day',
                    title:'日期'
                },
                {
                    key:'router',
                    dataIndex:'router',
                    title:'路由'
                },
                {
                    key:'duration',
                    dataIndex:'duration',
                    title:'接口执行时间'
                },
                {
                    key:'totalSql',
                    dataIndex:'totalSql',
                    title:'SQL总条数'
                },
                {
                    key:'totalSqlTime',
                    dataIndex:'totalSqlTime',
                    title:'SQL总时间'
                },
                {
                    key:'num',
                    dataIndex:'num',
                    title:'预警次数'
                }
            ],
            modalTable:[]
        }
    }
    componentDidMount() {
        // root才可以进行趋势的切换
        this.setState({
            isRoot:localStorage.getItem('username')==='root'
        })
        // console.log(localStorage.getItem('username')==='root')
        // 概况
        getOverview().then(data=>{
            console.log(data);
            this.setState({
                params:data.data.data
            },()=>{
                this._init()
            })
        })
        this._initPostParams();
        this._initPostParams2();
        // 云图访问分布
        // this._getYUntuData()
        // 系统报警趋势
        // this._getErrorData()

        this._getList1()
        this._getList2()
        this._getList3()


    }
    _getList1(){
        // 系统登录日志
        loginList({pageSize:this.state.pageSize,page:this.state.currentPage1}).then(data=>{
            console.log(data);
            this.setState({
                loginlistData:this._handleTableKey(data.data.list),
                loginTotal:data.data.pager.totalCount
            },()=>{
                this._initTable("login")
            })
        })
    }
    _getList2(){
        backstageList({pageSize:this.state.pageSize,page:this.state.currentPage2,type:2}).then(data=>{
            console.log(data)
            this.setState({
                visitListData:this._handleTableKey(data.data.list),
                visitTotal:data.data.pager.totalCount
            },()=>{
                this._initTable("cloud")
            })
        })
    }
    _getList3(){
        // 后台操作日志
        backstageList({pageSize:this.state.pageSize,page:this.state.currentPage3,type:1}).then(data=>{
            console.log(data)
            this.setState({
                backStageData:this._handleTableKey(data.data.list),
                backstageTotal:data.data.pager.totalCount
            },()=>{
                this._initTable("backend")
            })
        })
    }

    _handleTableKey = (list) => {
        let i = 1;
        list.map(item => {
            item["key"] = i;
            i++;
        })
        return list;
    };

    _initPostParams(){
        if(this.state.firstDate.length){
            // 传时间选择，timeRange,
            this.setState({
                postData1:{
                    timeRange:this.state.firstDate
                }
            },()=>{
                this._getYUntuData()
            })
        }else{
            // 传类型,type:1,2
            this.setState({
                postData1:{
                    timeType:this.state.activeBtn1
                }
            },()=>{
                this._getYUntuData()
            })
        }
    }
    _initPostParams2(){
        if(this.state.secondDate.length){
            // 传时间选择，timeRange
            this.setState({
                postData2:{
                    timeRange:this.state.secondDate,
                    type:this.state.activeBtn3
                }
            },()=>{
                this._getErrorData();
            })
        }else{
            // 传类型，type:1,2
            this.setState({
                postData2:{
                    timeType:this.state.activeBtn2,
                    type:this.state.activeBtn3
                }
            },()=>{
                this._getErrorData();
            })
        }
    }
    _getYUntuData(){
        yuntuVisit({ ...this.state.postData1}).then(data => {
            console.log(data)
            let xData = []
            let barData = []
            for(let i in data.data.list){
                xData.push(data.data.list[i].name)
                barData.push(data.data.list[i].value)
            }
            this._initLeftCharts(xData,barData);
        })
    }
    _getErrorData(){
        systemWarningLine({...this.state.postData2}).then(data=>{
            console.log(data)
            let xData = [];
            let lineData = []
            for(let i in data.data.list){
                xData.push(data.data.list[i].day)
                lineData.push(parseInt(data.data.list[i].value))
            }
            this._initRightCharts(xData,lineData);
        })
    }
    _init() {
        // 模块1
        let lists = [{
                key:'cloudNum',
                name: '云图访问总量',
                icon: require('../index/images/visit_times_icon.png'),
                per: '次',
                color:'aqua'
            },
            {
                key:'backendNum',
                name: '后台操作总量',
                icon: require('../index/images/backstage_icon.png'),
                per: '次',
                color:'chartreuse'
            },
            {
                key:'errorCatchNum',
                name: '异常捕获总量',
                icon: require('../index/images/jiekou_watch_icon.png'),
                per: '次',
                color:'chocolate'
            },
            {
                key:'apiWarningNum',
                name: '接口预警总量',
                icon: require('../index/images/error_jiekou_icon.png'),
                per: '次',
                color:'crimson'
            },
        ];
        let timesList = []
        for(let i in lists){
            timesList.push(
                <div className="small-card" key={i}>
                    <Card key={i}>
                        <div className="flex_all_center">
                            <img src={lists[i].icon} className='times_icon' alt=""/>
                            <div className='value_wraper'>
            <div className='times_value' style={{color:lists[i].color}}>{this.state.params[lists[i].key]}<span style={{fontSize:'16px',color:'black',fontWeight:400}}>{lists[i].per}</span></div>
                                <div className='times_title'>{lists[i].name}</div>
                            </div>
                        </div>
                    </Card>
                </div>
            )
        }
        this.setState({
            timesList:timesList
        })
    }
    _initTable(key){
        let listModule = [];
        listModule.push(
            <div key={key} className='flex_v_center'>
                    <div className='middle_card'>
                        <Card>
                            <div className='flex_v_center'>
                                <div className='chart_title_wraper flex_v_center'>{this.state.loginList.name}</div>
                            </div>
                            <Table pagination={false} columns={this.state.loginList.columns} dataSource={this.state.loginlistData} size="middle" />
                            <div className='pagination_wraper'>
                                <Pagination pageSize={this.state.pageSize} current={this.state.currentPage1} total={parseInt(this.state.loginTotal)} showTotal={(total)=>`共${total}条数据`} onChange={this.onChangePage1}/>
                            </div>

                        </Card>
                    </div>
                    <div className='middle_card'>
                        <Card>
                            <div className='flex_v_center'>
                                <div className='chart_title_wraper flex_v_center'>{this.state.yuntuVisitList.name}</div>
                            </div>
                            <Table pagination={false} columns={this.state.yuntuVisitList.columns} dataSource={this.state.visitListData} size="middle" />
                            <div className='pagination_wraper'>
                                <Pagination pageSize={this.state.pageSize} current={this.state.currentPage2} total={parseInt(this.state.visitTotal)} showTotal={(total)=>`共${total}条数据`} onChange={this.onChangePage2}/>
                            </div>
                        </Card>
                    </div>
                    <div className='middle_card'>
                        <Card>
                            <div className='flex_v_center'>
                                <div className='chart_title_wraper flex_v_center'>{this.state.backOperateList.name}</div>
                            </div>
                            <Table pagination={false} columns={this.state.backOperateList.columns} dataSource={this.state.backStageData} size="middle" />
                            <div className='pagination_wraper'>
                                <Pagination pageSize={this.state.pageSize} current={this.state.currentPage3} total={parseInt(this.state.backstageTotal)} showTotal={(total)=>`共${total}条数据`} onChange={this.onChangePage3}/>
                            </div>
                        </Card>
                    </div>
            </div>
        )
        this.setState({
            listModule:listModule
        })
    }
    _initLeftCharts (xData,yData){
        let timeSelectBtn = [
            {
                name:'近七天'
            },
            {
                name:"近30天"
            }
        ]
        let timeBtnShow = []
        for(let i in timeSelectBtn){
            timeBtnShow.push(
            <div key={i} className={`time_select_btn flex-all_center ${this.state.activeBtn1==(parseInt(i)+1)?'btn_actve':''}`} onClick={this.onbtnClick1.bind(this,i)}>{timeSelectBtn[i].name}</div>
            )
        }
        let leftChart = <div className='big_card'>
                        <Card>
                            <div className='title-wraper flex_v_center'>
                                <div className='chart_title_wraper flex_v_center'>{this.state.yuntuCharts.name}</div>
                                <div className=' flex_v_center'>
                                    <div className='flex_v_center'>{timeBtnShow}</div>
                                    <div className='date_picker_wraper'>
                                        <RangePicker
                                            onChange={this.onDateChange1}
                                            defaultValue={[moment(new Date(), dateFormat), moment(new Date(), dateFormat)]}
                                            format={dateFormat}
                                        />
                                    </div>
                                </div>
                            </div>
                            <div id='yuntuvisit' className="yuntu_chart"></div>
                        </Card>
                    </div>
        this.setState({
            leftChart:leftChart
        })
        let visitChart = echarts.init(document.getElementById('yuntuvisit'));
        let option = {
            tooltip: {},
            xAxis: {
                data: xData

            },
            grid:{
                width:780,
                height:230,
                left:30
            },
            color:["#239DFA"],
            yAxis: {
                name:'单位:(次)'
            },
            series: [{
                name: '云图访问分布',
                barWidth:20,
                type: 'bar',
                data: yData
            }]
        }
        visitChart.setOption(option)
        console.log(visitChart);
    }
    _initRightCharts(xData,yData){
        let icon = require('../index/images/xia_zuan_icon.png')
        let typeSelectBtn = []
        if(this.state.isRoot){
            typeSelectBtn = [
                {
                    name:'API',
                    disabled:true
                },
                {
                    name:'SQL',
                    disabled:this.state.isRoot
                },
            ]
        }
        let typeBtn = [];
        for(let i in typeSelectBtn){
            typeBtn.push(
            <div key={i} className={`time_select_btn flex_all_center ${this.state.activeBtn3==(parseInt(i)+1)?'btn_actve':''}`} onClick={this.onbtnClick3.bind(this,i)}>{typeSelectBtn[i].name}</div>
            )
        }
        let timeSelectBtn = [
            {
                name:'近七天'
            },
            {
                name:"近30天"
            }
        ]
        let timeBtnShow = [];
        for(let i in timeSelectBtn){
            timeBtnShow.push(
            <div key={i} className={`time_select_btn flex_all_center ${this.state.activeBtn2==(parseInt(i)+1)?'btn_actve':''}`} onClick={this.onbtnClick2.bind(this,i)}>{timeSelectBtn[i].name}</div>
            )
        }
        let rightChart = <div className='big_card'>
                        <Card>
                            <div className='title-wraper'>
                                <div className='chart_title_wraper'>{this.state.systemCharts.name} {this.state.isRoot?(<img className="xia_zuan_icon" onClick={this.showModal} src={icon} alt=""/>):''} </div>
                                <div className='select_btn_wraper flex_v_center'>
                                    <div className='flex_v_center type_select_wraper'>{typeBtn}</div>
                                    <div className='flex_v_center time_select_wraper'>{timeBtnShow}</div>
                                    <div className='date_picker_wraper'>
                                        <RangePicker
                                            onChange={this.onDateChange2}
                                            defaultValue={[moment(new Date(), dateFormat), moment(new Date(), dateFormat)]}
                                            format={dateFormat}
                                        />
                                    </div>
                                </div>
                            </div>
                            <div id='errorChart' className="yuntu_chart"></div>
                        </Card>
                    </div>
        this.setState({
            rightChart:rightChart
        })
        let errorChart = echarts.init(document.getElementById('errorChart'));
        let option = {
            tooltip: {},
            color:["#239DFA"],
            xAxis: {
                data: xData
            },
            grid:{
                width:780,
                height:230,
                left:30
            },
            yAxis: {
                name:'单位:(次)'
            },
            series: [{
                name: '系统报警趋势',
                type: 'line',
                data: yData
            }]
        }
        errorChart.setOption(option)
        console.log(errorChart);
    }
    _initModalCharts(list,total){
        let columns = []
        if(this.state.activeBtn3==1){
            columns = this.state.modalAPIColumns;
        }else{
            columns = this.state.modalSQLColumns;
        }
        let modalTable = [];
        modalTable.push(
            <div key="modal">
                <Table pagination={false} columns = { columns } dataSource = { list } size = "middle" />
                <div className="modal_paginnation_wraper">
                    <Pagination pageSize = {10} current = { this.state.currentPage4 } total = { parseInt(total) } showTotal = { (total) => `共${total}条数据` } onChange = { this.onChangePage4 }/>
                </div>

            </div>
        )
        this.setState({
            modalTable:modalTable
        })
    }
    onDateChange1 = (date,dateArr)=>{
        console.log(date,dateArr)
        this.setState({
            firstDate:dateArr
        },()=>{
            this.setState({
                activeBtn1:0
            },()=>{
                console.log(this.state.firstDate)
                this._initPostParams()
            })
        })
    }
    onDateChange2 = (date,dateArr)=>{
        console.log(date,dateArr)
        this.setState({
            secondDate:dateArr
        },()=>{
            this.setState({
                activeBtn2:0
            },()=>{
                this._initPostParams2()
            })
        })
    }
    showModal=()=>{
        this.setState({
            showModal:true
        },()=>{
            // 全部的报警趋势
            systemListData({ type: this.state.activeBtn3, timeDayRange: this.state.secondDate,page:this.state.currentPage4,pageSize:10,timeDayRange:this.secondDate }).then(data => {
                console.log(data)
                let total = data.data.pager.totalCount
                this._initModalCharts(data.data.list,total);
            })
        })

    }
    closeMOdal = ()=>{
        this.setState({
            showModal:false
        })
    }
    onbtnClick1 = (i)=>{
        console.log(typeof(i),i);
        this.setState({
            activeBtn1:parseInt(i)+1
        },()=>{
            console.log("state中activeBtn"+this.state.activeBtn1);
            this._initPostParams();
        })
    }
    onbtnClick2 = (i)=>{
        console.log("当前："+i);
        this.setState({
            activeBtn2:parseInt(i)+1
        },()=>{
            this._initPostParams2()
            console.log("state中activeBtn2"+this.state.activeBtn2)
        })
    }
    onbtnClick3 = (i)=>{
        if(i==0){
            this.setState({
                typeName:'API报警趋势'
            })
        }else{
            this.setState({
                typeName:'SQL报警趋势'
            })
        }
        this.setState({
            activeBtn3:parseInt(i)+1
        },()=>{
            this._initPostParams2()
            console.log("state中activeBtn2"+this.state.activeBtn2)
        })
    }
    onChangePage1 = (i)=>{
        this.setState({
            currentPage1:i
        },()=>{
            this._getList1()
        })
    }
    onChangePage2 = (i)=>{
        this.setState({
            currentPage2:i
        },()=>{
            this._getList2()
        })
    }
    onChangePage3 = (i)=>{
        this.setState({
            currentPage3:i
        },()=>{
            this._getList3()
        })
    }
    onChangePage4 = (i)=>{
        this.setState({
            currentPage4:i
        },()=>{
            this.showModal()
        })
    }
    render() {
        return (
            <div>
                <div className='flex_v_center'>
                    {this.state.timesList}
                </div>
                <div className="flex_v_center">
                    {this.state.leftChart}
                    {this.state.rightChart}
                </div>
                {/* <div className='flex_v_center'>
                    <div className='middle_card'>
                        <Card>
                            <div className='flex_v_center'>
                                <div className='chart_title_wraper flex_v_center'>{this.state.loginList.name}</div>
                            </div>
                            <Table pagination={false} columns={this.state.loginList.columns} dataSource={this.state.loginlistData} size="middle" />

                        </Card>
                    </div>
                    <div className='middle_card'>
                        <Card>
                            <div className='flex_v_center'>
                                <div className='chart_title_wraper flex_v_center'>{this.state.yuntuVisitList.name}</div>
                            </div>
                            <Table pagination={false} columns={this.state.yuntuVisitList.columns} dataSource={this.state.backStageData} size="middle" />
                        </Card>
                    </div>
                    <div className='middle_card'>
                        <Card>
                            <div className='flex_v_center'>
                                <div className='chart_title_wraper flex_v_center'>{this.state.backOperateList.name}</div>
                            </div>
                            <Table pagination={false} columns={this.state.backOperateList.columns} dataSource={this.state.backStageData} size="middle" />
                        </Card>
                    </div>
                </div> */}
                {this.state.listModule}
                <Modal width={1000} title={this.state.typeName} visible={this.state.showModal} onOk={this.closeMOdal} onCancel={this.closeMOdal}>
                    {this.state.modalTable}
                </Modal>
            </div>

        )
    }
}
export default HomeInfo
